using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nop.Core.Caching
{
	public class RedisCacheManager:ICacheManager, IRemoteLockProvider
	{
		private IRedisClientsManager _clientsManager;
		private Type stringType = typeof(String);

		public RedisCacheManager(IRedisClientsManager manager)
		{
			_clientsManager = manager;
		}

		public T Get<T>(string key)
		{
			using (var client = _clientsManager.GetClient())
			{
				return client.Get<T>(key);
			}
		}

		public void Set(string key, object data, int cacheTime)
		{
			using (var client = _clientsManager.GetClient())
			{
				client.Set(key, data, new TimeSpan(0, 0, cacheTime));
			}
		}

		public bool IsSet(string key)
		{
			using (var client = _clientsManager.GetClient())
			{
				return client.ContainsKey(key);
			}
		}

		public void Remove(string key)
		{
			using (var client = _clientsManager.GetClient())
			{
				client.Remove(key);
			}
		}

		public void RemoveByPattern(string pattern)
		{

		}

		public void Clear()
		{
			using (var client = _clientsManager.GetClient())
			{
				client.FlushDb();
			}
		}

		public void AcquireLockAndExecute(string key, int timeoutSeconds,  Action action)
		{
			using (var client = _clientsManager.GetClient())
			{
				using (client.AcquireLock(key, new TimeSpan(0,0,timeoutSeconds)))
				{
					action();
				}
			}
		}
	}
}
